# !/usr/bin/python
# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

import os
import re

print "Current path:" + os.getcwd()


def single_to_double (str):
    str=re.sub('[\'|\"]','\"',str)
    return str


def search_file(path, dir_name, file_name, target_dir_name):
    list = []
    for root, dirs, files in os.walk(path):
        if dir_name in dirs:
            values_folder_path = os.path.join(str(root), dir_name)
            target_folder_path = os.path.join(str(root), target_dir_name)
            for root, dirs, files in os.walk(values_folder_path):
                if file_name in files:
                    values_file_path = os.path.join(str(root), file_name)
                    target_file_path = os.path.join(str(target_folder_path), file_name)
                    list.append(values_file_path)
                    list.append(target_file_path)
                    list.append(values_folder_path)
                    list.append(target_folder_path)
    return list


def replace_property(line, scale):
    if isinstance(line , str):
        line = line.decode('utf-8')
    match = re.match(ur'(<.+?)(>.+?)(<.+?>)', line)

    if match is not None:
        yy = match.group(2)
        print type(yy)
        match_next = re.search(ur'\d+', yy)     #
        float_result = (int(match_next.group()) * scale)
        int_result = int(float_result)
        if (float_result - int_result >= 0.5) :
            result = int_result +1
        else :
            result = int_result
        #print line
        #print yy
        yy=yy.replace(match_next.group(),str(result))
        #print yy
        if isinstance(line , str):
            line= line.decode('utf-8')
        if isinstance(yy , str):
            yy=  yy.decode('utf-8')
        line = line.replace(match.group(2), yy)  # 注意！ 这里的int会影响结果的准确，如需准确数值，取消int转
        #print match.group(2)
    print repr(line)
    return line


def replace_file_none(fromdir, todir, magic_num):  # 目标文件夹无dimens文件，调用此函数
    with open(fromdir, "r") as f1, open(todir, "w") as f2:
        for line in f1:
            line =line.decode('utf-8')  #decode为Unicode
            flag=0
            line = replace_property(line, magic_num)
            ma1 = re.search(ur'(<.+?)(>)', line)  # 取源文件name内容
            if ma1 is not None:
                home_name = ma1.group(1)                                                              #新增
                if home_name==ur'<integer name="autostart_update_news_view_time"':                     #新增
                    flag += 1                                                                         #新增
            if flag==0: 
                print line
                line=line.encode('utf-8') #encode为UTF8,python默认写入string，如果不是string的类型，也会先转为str再写入，此时便有了转码的风险，不如自己先encode                                                                              #新增
                f2.write(line)                                                                          
        f1.close()
        f2.close()


def replace_file_exist(fromdir, todir, magic_num):  # 目标文件夹存在dimens文件，调用此函数补充未填行
    with open(fromdir, "r") as f1, open(todir, "r+") as f2:
        list2 = []
        change_todir = []

        for line2 in f2:
            line2 = line2.decode('utf-8') 
            if line2 is not None:  # 先读取所有目标文件下中已有内容，存入列表
                m = re.match(ur'</resources>', line2)  # 除了尾行的'</resources>'不要

                if m is None and line2 != ur'\n':
                    list2.append(line2)  # 其他全部按顺序载入列表
                    ma2 = re.search(ur'(<.+?)(>)', line2)
                    if ma2 is not None:
                        todir_name = ma2.group(1).decode('utf-8')  # 正则解析出name内容
                        change_todir.append(todir_name)
        for line1 in f1:
            line1=line1.decode('utf-8')
            flag = 0  # 标志位，如果为零，则无重复
            home_name = 0
            ma1 = re.search(ur'(<.+?)(>)', line1)  # 取源文件name内容
            if ma1 is not None:
                home_name = ma1.group(1).decode('utf-8')               
                #print home_name                                       
                #print type(home_name)
                if (home_name==ur'<integer name="autostart_update_news_view_time"'): #or (home_name == ur'<?xml version="1.0" encoding="utf-8"?')  :
                    flag += 1

            if change_todir is not None:
                for i in change_todir:  # 如果源文件的某行在目标文件中有匹配则 flag加1 导致这一行不会被重复写入

                    print type(home_name)
                    print type(i)

                    if isinstance(i,unicode):
                        i=single_to_double(i)
                    if isinstance(home_name,unicode):
                        home_name=single_to_double(home_name)
                    print (home_name==i)
                    if (home_name == i):
                        flag += 1

            if (flag == 0 and line1 != '\n'):
                line1 = replace_property(line1, magic_num)  # 替换为换算后的属性
                list2.append(line1)
        f2.seek(0)
        f2.truncate(0)
        for lingtem in list2:
            #if lingtem != ur'<?xml version="1.0" encoding="utf-8"?>\n' :
            lingtem = lingtem.encode('utf-8')
            f2.write(lingtem)
        f1.close()
        f2.close()


# 建立元组
# ===================================================================================
values_dic = {
    'values-sw533dp': '0.66',
    'values-sw600dp': '0.75',
    'values-sw800dp': '1',
    'values-sw685dp': '0.85',
    'values-sw914dp': '1.15',
    'values-sw450dp': '0.56',
    'values-sw400dp': '0.5',
}
home_folder = os.getcwd()

# 遍历字典
for target_folder, target_scale in values_dic.items():
    scale = float(target_scale)
    dimens_file_list = []
    dimens_file_list = search_file(home_folder, "values", "dimens.xml", target_folder)
    print "values folder:" + str(dimens_file_list)
    print "------------------------"
    list_length = len(dimens_file_list)
    i = 0
    print "target folder: " + target_folder + ", scale:" + target_scale
    while i < list_length:
        if (not (os.path.exists(dimens_file_list[i + 1]))):
            if (not (os.path.exists(dimens_file_list[i + 3]))):
                os.mkdir(dimens_file_list[i + 3])
            replace_file_none(dimens_file_list[i + 0], dimens_file_list[i + 1], scale)
            print "not"
            print dimens_file_list[i + 3] + ' DO ONT HAVE dimens.xml,create complete!'

        else:
            replace_file_exist(dimens_file_list[i + 0], dimens_file_list[i + 1], scale)
            print dimens_file_list[i + 3] + ' Exist dimens.xml,Added complete!'

        i = i + 4